package com.mango.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.CheckedTextView;

@SuppressLint("AppCompatCustomView")
public class HollowCheckedTextView extends CheckedTextView {
    private final RectF bounds = new RectF();
    private final PorterDuffXfermode porterDuffXfermode
            = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);

    private Drawable bgDrawable;

    public HollowCheckedTextView(Context context) {
        super(context);
    }

    public HollowCheckedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HollowCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //直接拿TextView的画笔即可
        TextPaint textPaint = getPaint();
        //设置一个颜色背景否则可能会有点透明
        textPaint.setColor(Color.BLACK);
        //画笔模式这里要设置为空哦，否则多次绘制将变得不正常
        textPaint.setXfermode(null);
        //保存一个图层，这是关键代码
        bounds.set(0, 0, getWidth(), getHeight());
        canvas.saveLayer(bounds, textPaint, Canvas.ALL_SAVE_FLAG);
        //绘制背景
        drawBackground(canvas);
        //給画笔设置DST_OUT模式，即将开始调用父类TextView的onDraw了
        textPaint.setXfermode(porterDuffXfermode);
        super.onDraw(canvas);
    }

    @Override
    public void setChecked(boolean checked) {
        super.setChecked(checked);
        if (bgDrawable == null) return;

        if (!checked)
            bgDrawable.setState(new int[]{android.R.attr.state_enabled});
        else
            bgDrawable.setState(new int[]{android.R.attr.state_enabled, android.R.attr.state_checked});
    }

    @Override
    public void setBackground(Drawable background) {
        //重写这个方法是为了不让父类中的背景被绘制出来，而是换成我们自己来绘制，这样背景还是可以利用Shape或者UI出图的方式实现
        bgDrawable = background;
        invalidate();
    }

    @Override
    public void setBackgroundResource(int resId) {
        setBackground(getContext().getResources().getDrawable(resId));
    }

    private void drawBackground(Canvas canvas) {
        final Drawable background = bgDrawable;
        if (background == null) return;

        background.setBounds(0, 0,
                getRight() - getLeft(),
                getBottom() - getTop());
        background.draw(canvas);
    }
}
